package com.bxkc.generator.utils;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * Velocity模板获取工具类
 * @author LCY
 */
public class VelocityTemplateUtils {

	private static VelocityEngine ve = null;

	static {
		ve = new VelocityEngine();
		// 可选值："class"--从classpath中读取，"file"--从文件系统中读取
		ve.setProperty("resource.loader", "class");
		// 如果从文件系统中读取模板，那么属性值为org.apache.velocity.runtime.resource.loader.FileResourceLoader
		ve.setProperty("class.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		Properties prop = new Properties();
		prop.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		prop.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		ve.init(prop);
	}


    /**
     * 将文件输出到指定目录
     * @param templatePath 模板路径 包名/文件名，示例 "code/entity.vm"
     * @param ctx  上下文内容，即代码中的各种变量属性，比如包名什么的
     *             示例：
     *             VelocityContext context = new VelocityContext();
     *             context.put("packagePath","具体值");
     *
     * @param outPath 文件输出目录，含文件名称
     */
	public static void writerFile(String templatePath, VelocityContext ctx,String outPath) {
        Template template = ve.getTemplate(templatePath);
		File file = new File(outPath);
        BufferedWriter writer = null;
        try {
            if (!file.exists()) {
                File fileParent = file.getParentFile();
                fileParent.mkdirs();
                file.createNewFile();
            }
            writer = new BufferedWriter( new FileWriter( file ) );
            template.merge(ctx, writer);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

	}


}
